from django.shortcuts import render
from django.views.generic import View
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from django.conf import settings
from adminApp.models import Information,InformationCategory,InformationComment
from authApp.models import UserInfo
from .forms import PubInformationForm
import os
# Create your views here.
class InformationPush(View):
    def get(self, request):
        print(request.user)
        # 返回渲染后的页面
        category = InformationCategory.objects.all()
        return render(request, 'push_content.html',{'category': category})

    def post(self, request):
        form = PubInformationForm(request.POST)
        if form.is_valid():
            title = form.cleaned_data.get('title')
            author_name = form.cleaned_data.get('author_name')
            content = form.cleaned_data.get('content')
            category_id = form.cleaned_data.get('category')
            data_source = form.cleaned_data.get('data_source')
            author_email = request.session['user_email']

            # Get the UserInfo instance matching the email
            author_instance = UserInfo.objects.get(email=author_email)
            category = InformationCategory.objects.get(id=category_id)
            infor = Information.objects.create(title=title, author_name=author_name,
                                       category=category, data_source=data_source,
                                       content=content, author=author_instance)
            return JsonResponse({'status': True, 'message': '内容发布成功！', 'data': {'infor_id': infor.id}})
        else:

            print(form.errors)
            return JsonResponse({'status': False, 'message': '参数错误！'})

class InformationUploadImage(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(*args, **kwargs)
    def post(self,request):

        file_data = request.FILES.get('image')
        keys = list(file_data.key())
        print(file_data)
        file_path = settings.BASE_DIR / 'media/upload/'
        if os.path.exists(file_path) is False:
            os.mkdir(file_path)
        data = []
        for key in keys:
            img_dict = {}
            file = file_data.get(f'{key}')
            new_path = os.path.join(file_path, file.name)
            with open(new_path,'wb+') as f:
                for chunk in file.chunks():
                    f.write(chunk)

            img_dict['url'] = f'/media/upload/{file.name}'
            data.append(img_dict)

        context = {"error": 0,"data": data}
        return JsonResponse(context)